package com.example.servicedemo;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    private static final String TAG =MyService.class.getSimpleName();
    private ServiceConnection mConn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }
    //进程  操作系统内独立运行的程序
    //线程 进程内独立运行的执行单元

    private void initView(){
        Button button=findViewById(R.id.butn_start_sevice);
        Button button1=findViewById(R.id.butn_stop_sevice);
        Button button2=findViewById(R.id.butn_onbind_sevice);
        Button button3=findViewById(R.id.butn_unbind_sevice);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //绑定服务
                mConn=new ServiceConnection() {
                    @Override
                    public void onServiceConnected(ComponentName name, IBinder service) {
                        //绑定成功

                        String text= ((MyService.MyBinder)service).getStr();
                        Log.d(TAG,"链接成功调用service返回的数据："+text);

                    }

                    @Override
                    public void onServiceDisconnected(ComponentName name) {
                        //解绑成功
                    }
                };
                //参数1 Intent负责绑定启动指定服务   参数2 绑定Service后的回调方法
                // 参数3  BIND_AUTO_CREATE  标识未服务如果未启动，则启动服务
                 bindService(new Intent(MainActivity.this,MyService.class),mConn,BIND_AUTO_CREATE);
            }
        });
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //解绑服务
                if (null!=mConn){
                    unbindService(mConn);
                }
                //释放serviceConnection
                mConn=null;
            }
        });
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startService(new Intent(MainActivity.this,MyService.class));
            }
        });

        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopService(new Intent(MainActivity.this,MyService.class));
            }
        });
    }
}